package kr.co.handysoft.net;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;

import kr.co.handysoft.compress.Archiving;
import net.sf.json.JSONObject;

public class FileInformationSenderHandler {

	private static String success;
	private static String fail;
	private static String id;
	private static String idKor;

	public static void invoke(File[] tgrFileArray, String successFolder, String failFolder) {
		success = successFolder;
		fail = failFolder;
		
		FileProcessResult result = new FileProcessResult(id, idKor);
		@SuppressWarnings("unchecked")
		ArrayList<ProcessFile> fileCollection = (ArrayList<ProcessFile>)result.get(Constant.FILES);
		
		for (File tgrFile : tgrFileArray){
			processFile(tgrFile, fileCollection);
		}
		
		if (fileCollection.size() > 0){
			communicateServer(result, fileCollection.size());
		}
	}

	private static void processFile(File tgrFile, ArrayList<ProcessFile> result) {
		if (!moveFile(tgrFile, success, result)){
			moveFile(tgrFile, fail, null);
		}
	}

	private static boolean moveFile(File tgrFile, String movePath, ArrayList<ProcessFile> collection) {
		String fileName = movePath + "/" + tgrFile.getName();
		try {
			
			copyFile(tgrFile, new File(fileName));
			
			if (collection != null){
				collection.add(new ProcessFile(tgrFile));
			}
			
			tgrFile.delete();	
			
			return true;
			   
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
	}

	private static void communicateServer(FileProcessResult tgrFile, int count) {
		try {
			System.out.println("server communication [ " + count + " files , " + Archiving.compress(JSONObject.fromObject(tgrFile).toString()).length + " bytes ]");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static void copyFile(File sourceFile, File destFile) throws IOException {
		 
		 FileChannel source = null;
		 FileChannel destination = null;
		 
		 try {			 
			 source = new FileInputStream(sourceFile).getChannel();
			 destination = new FileOutputStream(destFile).getChannel();
			 destination.transferFrom(source, 0, source.size());
		 }finally {
			 if(source != null) source.close();
			 if(destination != null) destination.close();
		 }
	}

	public static void setSystemId(String sId, String sIdKor) {
		id = sId;
		idKor = sIdKor;
	}

}
